import sys
import traceback

from flask import Flask, request

import api_console
import api_sys
import api_es
from zz import zz_code
from zz import zz_return

app = Flask(__name__)

app.register_blueprint(blueprint=api_console.app)
app.register_blueprint(blueprint=api_sys.app)
app.register_blueprint(blueprint=api_es.app)


@app.errorhandler(404)
def server_error404(error):
    r = zz_return.of(404, "404 Not Found")
    r.set_data("url", request.url)

    return r.to_json()


@app.errorhandler(Exception)
def internal_server_error(ex: Exception):
    # 获取当前调用栈
    exc_type, exc_value, exc_tb = sys.exc_info()
    # 获取错误发生的文件名和行号
    error_file_name, error_line_number, error_function, error_text = traceback.extract_tb(exc_tb)[-1]  # 获取到最后一个错误

    r = zz_return.of(500, error_text)
    r.set_data("url", request.url)
    r.set_data("file", f"{error_file_name}[{error_line_number}] in {error_function}")
    r.set_data("traceback", traceback.format_exc())
    traceback.print_exc()
    return r.to_json()


def is_debug():
    debug = zz_code.env("DEBUG", "0")
    return debug == '1'


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8110, debug=is_debug())
